package com.admin.dao;

import java.io.UnsupportedEncodingException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;

import org.json.JSONArray;
import org.json.JSONObject;
import org.springframework.stereotype.Service;

import com.admin.model.ChainGw;
import com.peersafe.chainsql.core.Chainsql;
import com.peersafe.chainsql.core.Submit.SyncCond;

@Service("ChainDao")
public class ChainDao {
	public static final Chainsql c = Chainsql.c;

	public void connect() {
		c.connect("ws://192.168.0.219:6006");
		c.as("raJ3ti7h82oG9gi3RYwbWWB42WsnubLabo", "shMZ3HTU1eCqTYtVNnD89FABsqqRq");
	}

	public HashMap<String, String> getLedger() {
		connect();
		JSONObject json = c.getLedger();

		return getMap(json);
	}

	public HashMap<String, String> getLedgerVersion() {
		connect();
		JSONObject json = c.getLedgerVersion();
		c.disconnect();
		return getMap(json);
	}

	public List<HashMap<String, Object>> getTransactions(String zh) throws UnsupportedEncodingException {
		connect();
		// JSONObject
		// json=c.getTransactions("r4eskeVjGWbYVq3JwBHzt6xXD3hrBE6pyb");
		JSONObject json = c.getTransactions(zh);
		if (json == null) {
			return null;
		}
		c.disconnect();
		return getTransactionsMap(json);
	}

	public HashMap<String, Object> getTransaction(String hash) throws UnsupportedEncodingException {
		connect();
		// JSONObject
		// json=c.getTransactions("r4eskeVjGWbYVq3JwBHzt6xXD3hrBE6pyb");
		JSONObject json = c.getTransaction(hash);
		if (json == null) {
			return null;
		}
		c.disconnect();
		return getTransactionMap(json);
	}

	private HashMap<String, Object> getTransactionMap(JSONObject json) throws UnsupportedEncodingException {
		HashMap<String, Object> map = new HashMap<String, Object>();
		String tablename = json.getJSONArray("Tables").getJSONObject(0).getJSONObject("Table").get("TableName")
				.toString();
		String Account = json.getString("Account");
		String sql = json.getString("Raw");
		map.put("tablename", tablename);
		map.put("Account", Account);
		net.sf.json.JSONArray jsonArray = net.sf.json.JSONArray.fromObject(sql);
		List<String> sqlList = new ArrayList<String>();
		for (int j = 0; j < jsonArray.size(); j++) {
			sqlList.add(new String(jsonArray.get(j).toString().getBytes(), "UTF-8"));
		}
		map.put("sqlList", sqlList);
		return map;
	}

	public List<HashMap<String, Object>> getTransactionsMap(JSONObject json) throws UnsupportedEncodingException {
		List<HashMap<String, Object>> list = new ArrayList<HashMap<String, Object>>();
		JSONArray array = json.getJSONArray("transactions");
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
		for (int i = 0; i < array.length(); i++) {

			String TransactionType = array.getJSONObject(i).getJSONObject("tx").getString("TransactionType");
			if (TransactionType.equals("SQLStatement")) {
				HashMap<String, Object> map = new HashMap<String, Object>();
				String tablename = array.getJSONObject(i).getJSONObject("tx").getJSONArray("Tables").getJSONObject(0)
						.getJSONObject("Table").get("TableName").toString();
				String Account = array.getJSONObject(i).getJSONObject("tx").getString("Account");
				String Owner = array.getJSONObject(i).getJSONObject("tx").getString("Owner");
				String sql = array.getJSONObject(i).getJSONObject("tx").getString("Raw");
				String date = sdf.format(new Date(array.getJSONObject(i).getJSONObject("tx").getLong("date")));
				/*
				 * try { sql= new String(sql.getBytes(), "UTF-8"); } catch
				 * (UnsupportedEncodingException e1) { // TODO Auto-generated
				 * catch block e1.printStackTrace(); }
				 */
				// List<Object> sqlList=
				// array.getJSONObject(i).getJSONObject("tx").getJSONArray("Raw").toList();
				net.sf.json.JSONArray jsonArray = net.sf.json.JSONArray.fromObject(sql);
				// List<String> sqlList= (List<String>)
				// net.sf.json.JSONArray.toList(jsonArray);
				List<String> sqlList = new ArrayList<String>();
				for (int j = 0; j < jsonArray.size(); j++) {
					sqlList.add(new String(jsonArray.get(j).toString().getBytes(), "UTF-8"));
					// System.out.println(jsonArray.get(j).toString());
				}
				/*
				 * System.out.println(tablename); System.out.println(Account);
				 * System.out.println(Owner); System.out.println(sqlList);
				 */
				map.put("tablename", tablename);
				map.put("Account", Account);
				map.put("Owner", Owner);
				map.put("date", date);
				map.put("sqlList", sqlList);
				list.add(map);
			}

			/*
			 * System.out.println(
			 * "===============================================");
			 * System.out.println(array.getJSONObject(i)); System.out.println(
			 * "===============================================");
			 */
		}

		return list;
	}

	public HashMap<String, String> getMap(JSONObject json) {
		HashMap<String, String> map = new HashMap<String, String>();
		Iterator<String> iterator = json.keys();
		while (iterator.hasNext()) {
			String key = (String) iterator.next();
			Object value = json.get(key);
			if (value instanceof JSONObject) {
				map.putAll(getMap((JSONObject) value));
			} else {
				map.put(key, value.toString());
			}
		}
		return map;
	}

	public  String saveChainGw(ChainGw gw) {
		connect();
		unicodeChainGw(gw);
		String sql="{'syh': '" + gw.getSyh() + "','wh': '" + gw.getWh() + "','bt':'"+gw.getBt()+"','tydjh':'"+gw.getTydjh()+"','xxsxq':'"+gw.getXxsxq()+"','djrq':'"+gw.getDjrq()+"','fwrq':'"+gw.getFwrq()+"','tjsj':'"+gw.getTjsj()+"','ssjg':'"+gw.getSsjg()+"','gkzrbm':'"+gw.getGkzrbm()+"','tjr':'"+gw.getTjr()+"','zwwjm':'"+gw.getZwwjm()+"','zwcclj':'"+gw.getZwcclj()+"','zwhash':'"+gw.getZwhash()+"'}";
		JSONObject json = c.table("gw").insert(c.array(sql))
				.submit(SyncCond.db_success);
		return json.getString("status");
	}
	private void unicodeChainGw(ChainGw gw) {
		if(gw.getBt()!=null){
			gw.setBt(unicode.string2Unicode(gw.getBt()));
		}
		if(gw.getSyh()!=null){
			gw.setSyh(unicode.string2Unicode(gw.getSyh()));
		}
		if(gw.getWh()!=null){
			gw.setWh(unicode.string2Unicode(gw.getWh()));
		}
		if(gw.getTydjh()!=null){
			gw.setTydjh(unicode.string2Unicode(gw.getTydjh()));
		}
		/*if(gw.getXxsxq()!=null){
			gw.setXxsxq(unicode.string2Unicode(gw.getXxsxq()));
		}
		if(gw.getDjrq()!=null){
			gw.setDjrq(unicode.string2Unicode(gw.getDjrq()));
		}
		if(gw.getFwrq()!=null){
			gw.setFwrq(unicode.string2Unicode(gw.getFwrq()));
		}*/
		if(gw.getSsjg()!=null){
			gw.setSsjg(unicode.string2Unicode(gw.getSsjg()));
		}
		if(gw.getGkzrbm()!=null){
			gw.setGkzrbm(unicode.string2Unicode(gw.getGkzrbm()));
		}
		/*
		if(gw.getTjr()!=null){
			gw.setTjr(unicode.string2Unicode(gw.getTjr()));
		}
		if(gw.getTjsj()!=null){
			gw.setTjsj(unicode.string2Unicode(gw.getTjsj()));
		}*/
		if(gw.getZwwjm()!=null){
			gw.setZwwjm(unicode.string2Unicode(gw.getZwwjm()));
		}
		/*
		if(gw.getZwcclj()!=null){
			gw.setZwcclj(unicode.string2Unicode(gw.getZwcclj()));
		}
		if(gw.getZwhash()!=null){
			gw.setZwhash(unicode.string2Unicode(gw.getZwhash()));
		}*/
	}

	public String updateChainGw(int id) {
		connect();
		ArrayList<String> l=new ArrayList<String>();
		l.add("{'status':1}");
		String str="{'id': "+id+"}";
		JSONObject json = c.table("gw").get(c.array(str)).update(l).submit(SyncCond.db_success);
		return json.getString("status");
	}
	public static void main(String[] args) throws UnsupportedEncodingException {
		ChainDao d = new ChainDao();
		//System.out.println(d.getTransaction("9ED7672E01B8A50F29F1919D77E892C5E1CE64CDFB449E6701E46F499E24E6D1"));
//		ChainGw gw=new ChainGw();
//		gw.setId(0);
//		gw.setBt("湖南省");
//		gw.setSyh("sdfdf");
//		gw.setWh("sdfd");
//		gw.setFwrq("2017-08-23");
//		gw.setTjsj("2017-08-23");
//		gw.setZwwjm("新建 Microsoft Excel 工作表 (2).xlsx");
//		gw.setZwcclj("D:\\\\Program Files\\\\Apache Software Foundation\\\\Tomcat 8.5\\\\webapps\\\\uploadFiles\\\\GW\\\\1503460656582-新建 Microsoft Excel 工作表 (2).xlsx");
//		//gw.setZwcclj("D:\\\\");
//		System.out.println(gw.getZwcclj().length());
//		gw.setZwhash("f8d213a82661edeabd7f2886416320880366b9ee");
//		System.out.println(d.saveChainGw(gw));
		d.updateChainGw(43);
	}


}
